package com.test.platform.service.publish;

import com.test.platform.dao.PublishInfoMapper;
import com.test.platform.model.PublishInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value; 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import com.test.platform.websocket.WebSocketService;  // 添加 WebSocketService 导入
import com.test.platform.websocket.WebSocketMessage;  // 添加 WebSocketMessage 导入

@Service
public class PublishInfoService {
    @Value("${publish.info.update.enabled}")
    private boolean publishInfoUpdateEnabled;
    
    // 使用 GitOperationService 替代直接依赖
    private static final Logger logger = LoggerFactory.getLogger(PublishInfoService.class);
    
    @Autowired
    private WebSocketService webSocketService;

    @Autowired
    private PublishExecutionService publishExecutionService;
    
    @Autowired
    private PublishInfoMapper publishInfoMapper;
    
    public List<PublishInfo> getAllPublishInfos() {
        return publishInfoMapper.findAll();
    }
    
    public PublishInfo getPublishInfoById(Integer id) {
        return publishInfoMapper.findById(id);
    }
    
    // 删除不需要的reorderIds方法
    
    @Transactional
    public boolean createPublishInfo(PublishInfo publishInfo) {
        try {
            logger.info("创建新的发布信息: owner={}, name={}, version={}", 
                publishInfo.getOwner(), publishInfo.getName(), publishInfo.getVersion());
            boolean result = publishInfoMapper.insert(publishInfo) > 0;
            if (result) {
                logger.info("✅ 发布信息创建成功: ID={}, owner={}, name={}, version={}", 
                    publishInfo.getId(), publishInfo.getOwner(), publishInfo.getName(), publishInfo.getVersion());
                // 通过WebSocket通知前端刷新
                webSocketService.sendMessage("refresh", new WebSocketMessage("refresh", null, "新的发布信息已添加"));
            } else {
                logger.warn("❌ 发布信息创建失败");
            }
            return result;
        } catch (Exception e) {
            logger.error("❌ 创建发布信息失败: {}", publishInfo, e);
            throw new RuntimeException("创建发布信息失败: " + e.getMessage());
        }
    }

    @Transactional
    public boolean deletePublishInfo(Integer id) {
        try {
            // 简单删除，不再需要重排ID
            return publishInfoMapper.deleteById(id) > 0;
        } catch (Exception e) {
            logger.error("删除发布信息失败", e);
            return false;
        }
    }

    @Transactional
    public boolean updatePublishInfo(PublishInfo publishInfo) {
        try {
            logger.info("更新发布信息: {}", publishInfo);
            // 直接传入 PublishInfo 对象
            return publishInfoMapper.update(publishInfo) > 0;
        } catch (Exception e) {
            logger.error("更新发布信息失败: {}", publishInfo, e);
            throw new RuntimeException("更新发布信息失败: " + e.getMessage());
        }
    }

    // 删除不需要的reorderPublishInfos方法
    @Transactional
    public void reorderPublishInfos() {
        publishInfoMapper.reorderIds();
    }

    public boolean toggleUpdateEnabled() {
        try {
            publishInfoUpdateEnabled = !publishInfoUpdateEnabled;
            // 如果启用，只更新发布相关的信息
            if (publishInfoUpdateEnabled) {
                updateAllPublishInfos();
            }
            return publishInfoUpdateEnabled;
        } catch (Exception e) {
            logger.error("切换发布信息更新功能状态失败", e);
            throw e;
        }
    }

    private void updateAllPublishInfos() {
        logger.info("开始更新所有发布信息...");
        List<PublishInfo> publishInfos = publishInfoMapper.findAll();
        for (PublishInfo info : publishInfos) {
            try {
                // 只更新发布状态相关的信息
                updatePublishStatus(info);
            } catch (Exception e) {
                logger.error("更新发布信息失败: {}", info, e);
            }
        }
        logger.info("发布信息更新完成");
    }

    private void updatePublishStatus(PublishInfo info) {
        // 这里添加更新发布状态的具体逻辑
        // 例如：检查发布状态、更新发布进度等
    }

    public boolean isUpdateEnabled() {
        return publishInfoUpdateEnabled;
    }

    @Transactional
    public boolean publish(String owner, String name) {
        // 根据 owner 和 name 查找对应的发布信息
        List<PublishInfo> publishInfos = publishInfoMapper.findByOwnerAndName(owner, name);
        if (publishInfos == null || publishInfos.isEmpty()) {
            throw new RuntimeException("未找到对应的发布信息");
        }
        
        // 获取最新的发布信息（ID最大的）
        PublishInfo publishInfo = publishInfos.stream()
                .max((a, b) -> a.getId().compareTo(b.getId()))
                .get();

        if ("审核中".equals(publishInfo.getStatus())) {
            throw new RuntimeException("该版本已经发布");
        }

        // 创建一个完整的回调实现
        PublishExecutionService.ProgressCallback callback = new PublishExecutionService.ProgressCallback() {
            @Override
            public void onProgress(PublishExecutionService.ExecutionStatus status, String message) {
                // 通过 WebSocket 发送进度消息
                webSocketService.sendMessage("progress", new WebSocketMessage("progress", status, message));
            }

            @Override
            public boolean onConfirmation(String message) {
                try {
                    // 通过 WebSocket 发送确认请求
                    WebSocketMessage confirmRequest = new WebSocketMessage("confirm", null, message);
                    webSocketService.sendMessage("confirm", confirmRequest);
                    
                    // 等待用户响应
                    CompletableFuture<Boolean> future = new CompletableFuture<>();
                    webSocketService.setConfirmationCallback(result -> future.complete(result));
                    
                    // 设置超时时间（例如30秒）
                    return future.get(30, TimeUnit.SECONDS);
                } catch (Exception e) {
                    logger.error("等待用户确认时发生错误", e);
                    return false;
                }
            }
        };

        boolean success = publishExecutionService.publishPackage(publishInfo, callback);
        if (success) {
            publishInfo.setStatus("审核中");
            // 直接传入 PublishInfo 对象
            publishInfoMapper.update(publishInfo);
        }
        return success;
    }

    @Transactional
    public boolean batchPublish(List<Map<String, String>> publishItems) {
        boolean allSuccess = true;
        for (Map<String, String> item : publishItems) {
            try {
                String owner = item.get("owner");
                String name = item.get("name");
                if (!publish(owner, name)) {
                    allSuccess = false;
                    logger.error("批量发布失败，owner: {}, name: {}", owner, name);
                }
            } catch (Exception e) {
                allSuccess = false;
                logger.error("批量发布失败，项目: {}, 错误: {}", item, e.getMessage());
            }
        }
        return allSuccess;
    }
    
    // 添加搜索方法
    public List<PublishInfo> findByOwner(String owner) {
        return publishInfoMapper.findByOwner(owner);
    }

    public List<PublishInfo> findByName(String name) {
        return publishInfoMapper.findByName(name);
    }

    public List<PublishInfo> findByOwnerAndName(String owner, String name) {
        return publishInfoMapper.findByOwnerAndName(owner, name);
    }
}